<template>
  <div class="item-one" ref="itemOne">
    <div class="title">
      <span>正佳订单查询</span>
      <div class="buttomStyle">
        <el-upload
          :headers="uploadHeaders"
          :show-file-list="false"
          class="upload-demo"
          :action="zjuploadshubi"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
          accept=".xlsx"
        >
          <el-button size="small" type="primary">上传数币订单</el-button>
        </el-upload>
        <el-upload
          :headers="uploadHeaders"
          :show-file-list="false"
          class="upload-demo2"
          :action="zjuploadyhk"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
          accept=".xlsx"
        >
          <el-button size="small" type="primary">上传银行卡订单</el-button>
        </el-upload>

        <el-button
          class="daochustyle"
          type="primary"
          :disabled="exxxx"
          @click="SplitOrderExcel()"
          ><i class="el-icon-download"></i>导出</el-button
        >

        <el-button icon="el-icon-refresh"></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
            <el-date-picker
              v-model="date"
              type="datetimerange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :clearable="false"
              :default-time="['00:00:00', '23:59:59']"
            >
            </el-date-picker>
          </div>
          <div class="leftitem">
            <el-select
              class="width20"
              v-model="orderType"
              placeholder="订单类型"
            >
              <el-option keys="1" label="条码" value="1"></el-option>
              <el-option keys="1" label="刷卡" value="2"></el-option>
              <el-option keys="1" label="数币" value="3"></el-option>
            </el-select>
            <el-input
              class="merchants width60"
              v-model.trim="orderNo"
              placeholder="订单号"
            ></el-input>
          </div>
        </div>
        <div class="rightBox">
          <div
            class="rightitem"
            v-if="userinfo.rolesId != 5 && userinfo.rolesId != 6"
          >
            <el-form ref="conditions" :model="conditions" label-width="80px">
              <el-input
                class="width60"
                v-model.trim="merchantNo"
                placeholder="商户号"
              ></el-input>
              <el-input
                class="width60"
                v-model.trim="merchantName"
                placeholder="商户名称"
              ></el-input>
            </el-form>
          </div>
          <div class="rightitem">
            <div class="block">
              <el-form label-width="80px">
                <el-input
                  class="width60"
                  v-model.trim="terminalNo"
                  placeholder="终端号"
                ></el-input>
              </el-form>
            </div>
          </div>
          <div class="rightitem">
            <el-button
              :disabled="sosobtn"
              icon="el-icon-search"
              type="primary"
              @click="soso"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" type="primary" @click="reset"
              >重置</el-button
            >
          </div>
        </div>
      </div>
      <div class="stitle">合计:</div>
      <div class="statistical">
        <div class="statisticalitem">
          <div>实收金额</div>
          <div>
            <span class="red">{{ indentinfo.balance }}</span> 元
          </div>
        </div>
        <div class="statisticalitem">
          <div>总手续费</div>
          <div>
            <span class="red">{{ indentinfo.fee }}</span> 元
          </div>
        </div>
        <div class="statisticalitem">
          <div>总结算金额</div>
          <div>
            <span class="red">{{ indentinfo.receiptAmount }}</span> 元
          </div>
        </div>
        <div class="statisticalitem">
          <div>总交易笔数</div>
          <div>
            <span class="red">{{ indentinfo.count }}</span> 笔
          </div>
        </div>
      </div>
      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="merchantarr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            align="center"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column
            label="商户号?商户名称"
            align="center"
            width="220"
            :render-header="renderheader"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.merchantNo }}</div>
              <div>{{ scope.row.merchantName }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="shopName"
            align="center"
            label="门店名称"
          ></el-table-column>
          <el-table-column
            label="订单类型?订单号"
            align="center"
            width="220"
            :render-header="renderheader"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.orderType == 1">条码</div>
              <div v-if="scope.row.orderType == 2">刷卡</div>
              <div v-if="scope.row.orderType == 3">数币</div>
              <div>
                {{ scope.row.orderNo }}
                <i
                  class="el-icon-copy-document iconmove"
                  @click="copyChannelTradeNoFunc(scope.row.orderNo)"
                  v-clipboard:copy="copyorderNo"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="balance"
            align="center"
            label="实收金额"
          ></el-table-column>
          <el-table-column
            prop="tradeAmount"
            align="center"
            label="交易金额"
          ></el-table-column>
          <el-table-column
            prop="fee"
            align="center"
            label="手续费"
          ></el-table-column>
          <el-table-column
            prop="status"
            align="center"
            label="支付状态"
          ></el-table-column>
          <el-table-column
            prop="type"
            align="center"
            label="业务类型"
          ></el-table-column>

          <el-table-column
            prop="terminalNo"
            align="center"
            label="终端号"
          ></el-table-column>
          <el-table-column
            prop="tradeTime"
            align="center"
            label="交易时间"
          ></el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="120"
          >
            <!-- <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="
                  joinindentdetails(scope.row.id, scope.row.payStatusCode)
                "
                >详情</el-button
              >
            </template> -->
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-size="10"
            :current-page.sync="cur_page"
            layout="total, sizes, prev, pager, next, jumper"
            :total="combined"
          ></el-pagination>
        </div>
      </div>
      <br />
      <br />
    </div>
  </div>
</template>

<script>
import {
  APIzjbill,
  APIzjbillstatistics,
  APIzjbillexcel,
  getservice,
  getBD,
  queryorder,
  dictionarylist,
} from "@/api/api";
export default {
  name: "item-one",
  data: function () {
    return {
      copyorderNo:'',
      orderType: "", //订单类型
      orderNo: "", //订单号
      merchantNo: "", //商户号
      terminalNo: "", //终端号
      merchantName: "", //商户名称
      loading: true,
      zjuploadshubi:
        process.env.VUE_APP_BASE_URL + "/product/v31/api/zjbill/upload/shubi",
      zjuploadyhk:
        process.env.VUE_APP_BASE_URL + "/product/v31/api/zjbill/upload/card",
      uploadHeaders: { token: sessionStorage.getItem("token") },

      cur_page: 1,
      cur_size: 10,
      multipleSelection: [],
      exxxx: false,
      sosobtn: false,
      servicearr1: [],
      servicearr2: [],
      merchantarr: [],
      combined: 10,
      pageCount: "",
      date: "",
      userinfo: "",
      indentinfo: {},
      channelslist: [],
      pickerOptions: {
        disabledDate(time) {
          let nowDate = new Date();
          let date = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            date: nowDate.getDate(),
          };
          let timeDate =
            date.year + "-" + date.month + "-" + date.date + " 23:59:59";
          let times = new Date(timeDate).getTime();
          return time.getTime() > times;
        },
      },
    };
  },
  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));
    this.$store.dispatch("getNewNum", 6);
    var day = new Date(); 
    day.setTime(day.getTime() - 24 * 60 * 60 * 1000); 
    var time = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + day.getDate(); 


    const date1 = time+ " 00:00:00";
    const date2 = time + " 23:59:59";
    this.date = [date1, date2];
    this.orderpage();
    this.dictionarylist();
    // 根据角色区别模糊搜索内容
    if (this.userinfo.rolesId == 2 || this.userinfo.rolesId == 3) {
      getservice({
        type: 2,
        parentid: this.userinfo.fid,
      }).then((res) => {
        for (var i = 0; i < res.data.rows.length; i++) {
          this.servicearr2.push({
            value: res.data.rows[i].agentname,
            id: res.data.rows[i].id,
          });
        }
      });
      this.getBD(this.userinfo.fid);
    } else if (this.userinfo.rolesId == 5) {
      this.conditions.merchantId = this.userinfo.fid;
    }
  },
  methods: {
       //复制订单号
    copyChannelTradeNoFunc(item){
      this.copyorderNo = item.replace(/^\s+|\s+$/g, "");
    },
     onCopy: function (e) {
      this.$message({
        message: "复制成功",
        type: "success",
      });
      console.log("复制成功");
    },
    onError: function (e) {
      this.$message.error("复制失败");
      console.log("复制失败");
    },
    //上传数币订单
    beforeUpload(file) {
      const isExcel =
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        file.type === "application/vnd.ms-excel";
      if (!isExcel) {
        this.$message.error("上传的文件不是Excel!");
      }
      return isExcel;
    },
    handleSuccess(response, file, fileList) {
      // TODO: 处理上传成功后的逻辑，response 是服务器返回的响应
      if (response.code == 200) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
      } else {
        this.$message({
          message: response.message,
          type: "warning",
        });
      }
      console.log("文件上传成功", response);
    },
    // 获取所有通道type
    dictionarylist() {
      dictionarylist({
        type: "channelType",
        status: 0,
        sort: "sorted",
        order: "DESC",
      }).then((res) => {
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.channelslist = res.data;
        }
      });
    },
    //修改thead 背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
      }
    },
    // 刷新
    refresh() {
      this.$router.go({
        path: 0,
        query: {
          t: Date.now(),
        },
      });
    },
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("?")[0]),
        h("br"),
        h("span", {}, column.label.split("?")[1]),
      ]);
    },
    // 分页导航
    handleCurrentChange(val) {
      this.cur_page = val;
      this.orderpage();
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    // 分页数量
    sizechange(val) {
      this.cur_size = val;
      this.orderpage();

      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    //多选框
    handleSelectionChange(val) {
      // console.log(val);
      this.multipleSelection = val;
    },
    //  重置
    reset() {
      const start = new Date();
      start.setTime(start.getTime());
      const year = start.getFullYear();
      let month = start.getMonth() + 1;
      if (month < 10) {
        month = "0" + month;
      }
      let date = start.getDate();
      if (date < 10) {
        date = "0" + date;
      }
      const date1 = year + "-" + month + "-" + date + " 00:00:00";
      const date2 = year + "-" + month + "-" + date + " 23:59:59";
      this.date = [date1, date2];
      this.cur_page = 1;

      this.orderType = ""; //订单类型
      this.orderNo = ""; //订单号
      this.merchantNo = ""; //商户号
      this.terminalNo = ""; //终端号
      this.merchantName = ""; //商户名称
    },
    // 搜索
    soso() {
      if (
        this.date == null ||
        this.date.length == 0 ||
        this.date == undefined
      ) {
        this.$message.error("查询时间不能为空");
        return;
      }
      this.cur_page = 1;
      this.sosobtn = true;
      this.orderpage();
    },
    // 一级服务商
    querySearch(queryString, cb) {
      let sosolist = {};
      sosolist = {
        page: 1,
        size: 20,
        type: 1,
        keywords: this.conditions.agent1,
      };
      getservice(sosolist).then((res) => {
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.servicearr1 = [];
          for (var i = 0; i < res.data.rows.length; i++) {
            this.servicearr1.push({
              value: res.data.rows[i].agentname,
              id: res.data.rows[i].id,
            });
          }
          let results = queryString
            ? this.servicearr1.filter(this.createFilter(queryString))
            : this.servicearr1;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }
      });
    },
    // 二级服务商
    querySearch2(queryString, cb) {
      let servicearr = this.servicearr2;
      let sosolist = {};
      sosolist = {
        page: 1,
        size: 20,
        type: 2,
        keywords: this.conditions.agent2,
      };
      getservice(sosolist).then((res) => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.servicearr2 = [];
          for (var i = 0; i < res.data.rows.length; i++) {
            this.servicearr2.push({
              value: res.data.rows[i].agentname,
              id: res.data.rows[i].id,
            });
          }
          let results = queryString
            ? this.servicearr2.filter(this.createFilter(queryString))
            : this.servicearr2;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }
      });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    // 获取一级服务商
    getservice(val) {
      getservice({
        type: val,
      }).then((res) => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else if (res.code == 200) {
          for (var i = 0; i < res.data.rows.length; i++) {
            this.servicearr1.push({
              value: res.data.rows[i].agentname,
              id: res.data.rows[i].id,
            });
          }
        }
      });
    },

    // 订单列表
    orderpage() {
      let sosolist = {};
      sosolist = {
        page: this.cur_page,
        size: this.cur_size,
        startTime: this.date[0],
        finishTime: this.date[1],

        orderType: this.orderType, //订单类型
        orderNo: this.orderNo, //订单号
        merchantNo: this.merchantNo, //商户号
        terminalNo: this.terminalNo, //终端号
        merchantName: this.merchantName, //商户名称
      };
      console.log(sosolist);

      APIzjbill(sosolist).then((res) => {
        console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else if (res.code != 200) {
          this.$message.error(res.message);
        } else {
          this.sosobtn = false;
          this.merchantarr = res.data;
          this.combined = res.pageInfo.recordCount;
          this.pageCount = res.pageInfo.pageCount;
          this.loading = false;
        }
      });
      APIzjbillstatistics(sosolist).then((res) => {
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.indentinfo = res.data;
        }
      });
      //   }
    },
    // 跳详情
    joinindentdetails(val, code) {
      if (code == 2 || code == 3 || code == 4 || code == 6 || code == 8) {
        queryorder({}, val).then((res) => {});
      }
      this.$router.push({
        path: "/indentdetails",
        query: {
          no: val,
        },
      });
    },
    // 导出
    SplitOrderExcel() {
      this.eeeex = true;
      let i = 0;
      let time = setInterval(() => {
        if (i == 60) {
          loading.close();
          this.$message.error("请求超时");
          clearInterval(time);
        } else {
          i++;
        }
      }, 1000);
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let sosolist = (sosolist = {
        startTime: this.date[0],
        finishTime: this.date[1],
        orderType: this.orderType, //订单类型
        orderNo: this.orderNo, //订单号
        merchantNo: this.merchantNo, //商户号
        terminalNo: this.terminalNo, //终端号
        merchantName: this.merchantName, //商户名称
      });
      APIzjbillexcel(sosolist).then((res) => {
        if (res.code == 405) {
          clearInterval(time);
          sessionStorage.removeItem("token");
          this.$router.push("/login");
          loading.close();
          this.exxxx = false;
        } else if (res.code == 200) {
          clearInterval(time);
          let elink = document.createElement("a");
          elink.download = "分账订单.xls";
          // elink.href = res.data;
          elink.href = res.data.replace("http://", "https://");
          elink.click();
          loading.close();
          this.exxxx = false;
        } else {
          clearInterval(time);
          this.$message.error(res.message);
          loading.close();
          this.exxxx = false;
        }
      });
    },

    // 跳转导出
    joinexportlist() {
      this.$router.push({
        path: "/exportlist",
        query: {
          type: "indent",
          exportType: 1,
        },
      });
    },
  },
};
</script>
<style scoped lang="less">
.iconmove {
  cursor: pointer;
}
.daochustyle {
  height: 33px;
  margin-left: 10px;
}
.buttomStyle {
  display: flex;
}
.upload-demo /deep/ .el-upload--text {
  border: 1px dashed #fff;
  width: 105px;
  height: 35px;
}
.upload-demo2 /deep/ .el-upload--text {
  margin-left: 10px;
  border: 1px dashed #fff;
  width: 114px;
  height: 35px;
}
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.tableBox {
  margin-top: 20px;
}
.servicename {
  width: 60%;
}
.servicelevel {
  width: 20%;
}
.width20 {
  width: 20%;
}
.width30 {
  width: 30%;
}
.red {
  color: #f9607d;
}
.stitle {
  padding: 5px 0;
  font-size: 18px;
}
.statistical {
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: #00152a;
  color: #fff;
  padding: 12px;
  box-sizing: border-box;
}
.statistical > .statisticalitem {
  text-align: center;
  line-height: 200%;
}
.BDname {
  width: 20%;
}
.width60 {
  width: 40%;
}
.yuan {
  color: #c1c5cb;
  font-size: 12px;
  position: relative;
  left: -20px;
}
.green {
  background: #97c05c;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.orange {
  background: #f29c38;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.hui {
  background: #888888;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.reds {
  background: #d3362f;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.blue {
  background: #4154af !important;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.cyan {
  background: rgba(1, 255, 255) !important;
  color: #fff;
  padding: 0 5px;
  border-radius: 10px;
}
.yellow {
  background: #ffe793 !important;
  color: #000;
  padding: 0 5px;
  border-radius: 10px;
}
.notice-tip {
  color: red;
  font-size: 8px;
  text-align: center;
}
.el-divider--horizontal {
  margin: 0;
  margin-top: -20px;
  margin-bottom: 15px;
}
/deep/.el-input--small .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.diver2th {
  margin-top: 15px;
}
.elForm {
  margin-left: 25px;
}
/deep/.dateTime .el-input--small .el-input__inner {
  width: 281px;
}
</style>